<?php

namespace app\admin\controller;

use think\captcha\Captcha;
use think\Controller;
use think\Session;

class Login extends Controller
{
  //登录界面
  public function index()
  {
    Session::delete('admin');
    $this->assign('admin_name',config('webset.ADMIN_NAME'));
    return $this->fetch('/login');
  }
  // 验证码生成
  public function captcha(){
    $config =    [
        // 验证码字体大小
        'fontSize'    =>    40,    
        // 验证码位数
        'length'      =>    4,   
        // 关闭验证码杂点
        'useNoise'    =>    false, 
    ];
    
    $captcha = new Captcha($config);
    return $captcha->entry();
  }
  //登录验证账号密码
  public function data(){
    $value = input('post.');
    $captcha = new Captcha();
    if(!$captcha->check($value['captcha']))return ['code'=>0,'msg'=>'验证码错误'];
    $admin = trim($value['admin']);
    $pwd = trim($value['pwd']);
    //查询当前用户
    $s = db('admin')->where(['is_del'=>0,'admin'=>$admin])->count();
    //判断有没有超级管理
    $num = db('admin')->where(['is_del'=>0,'superadmin'=>1])->count();
    if($num == 0&&$s ==0){
      $data['admin'] = $admin;
      $data['inTime'] = $data['upTime'] = time();
      $data['key'] = sha1($data['inTime']);
      $data['pwd'] = sha1($pwd.$data['key']);
      $data['superadmin'] = 1;
      $data['role'] = 0;
      $id = db('admin')->insertGetId($data);
      Session::set('admin',$id);
      return ['code'=>1,'msg'=>'登录成功'];
    }else{
      $data = db('admin')->field('admin,pwd,key,state,id')->where(['is_del'=>0,'admin'=>$admin])->find();
      if($data['pwd'] != sha1($pwd.$data['key']))return ['code'=>0,'msg'=>'账号或密码错误'];
      if($data['state'] != 1)return ['code'=>0,'msg'=>'该账号异常'];
      Session::set('admin',$data['id']);
      return ['code'=>1,'msg'=>'登录成功'];
    }

  }
  //没有权限页面
  public function nopower(){
    return $this->fetch('/nopower');
  }

  
}
